package org.springblade.modules.admin.utils;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author zcc
 * @version 1.0
 * @date 2021/5/26 11:39
 */
@Component
@Slf4j
public class WeiXinUtil {
	@Resource
	private  RedisTemplate<String, Object> redisTemplate;

	private final static String WEI_XIN_ACCESS_TOKEN= "WEI_XIN_ACCESS_TOKEN";

	private final static String WEI_ACCESS_TOKEN_URL = " https://api.weixin.qq.com/cgi-bin/token";

	private final static String WEI_SEND_TEMPLATE = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=";

	@Value("${weixin.appId}")
	private String appId;

	@Value("${weixin.appSecret}")
	private String appSecret;


	/**
	 * 开发文档:https://mp.weixin.qq.com/advanced/tmplmsg?action=faq&token=1607844269&lang=zh_CN
	 * org.springblade.modules.admin.vo.weixin.MessageTemplateVO
	 * 发送公众号模板消息
	 * @param body json数据 例如：MessageTemplateVO
	 * @return 发送结果集
	 */
	public String sendTemplateMessage(String body){

		String accessToken  = (String)redisTemplate.opsForValue().get(WEI_XIN_ACCESS_TOKEN);
		if(StrUtil.isEmpty(accessToken)){
			Map<String,Object> map = new HashMap<>(16);
			map.put("grant_type","client_credential");
			map.put("appid",appId);
			map.put("secret",appSecret);
			String s = HttpUtil.get(WEI_ACCESS_TOKEN_URL, map);
			log.info("==============发送模板消息获取token信息===="+s);
			Map resultMap = JSON.parseObject(s, Map.class);
			accessToken = Convert.toStr(resultMap.get("access_token"));
			redisTemplate.opsForValue().set(WEI_XIN_ACCESS_TOKEN,accessToken, Convert.toLong(resultMap.get("expires_in")), TimeUnit.SECONDS);
		}
		return HttpUtil.createPost(WEI_SEND_TEMPLATE + accessToken).body(body).execute().body();
	}
}
